package com.boardour.wifip2p.receiver;

import android.content.Context;
import android.net.wifi.p2p.WifiP2pDevice;

import com.boardour.wifip2p.WifiP2pCommon;

/**
 * WifiP2p管理类
 */
public class ConnectManager implements IConnectListener {
    private ConnectionReceiver connectionReceiver;
    private IConnectListener connectListener;
    /**
     * WifiP2p是否可用
     */
    private boolean wifiP2pEnable;
    /**
     * 是否创建群
     */
    private boolean wifiP2pConnect;
    private WifiP2pDevice wifiP2pDevice;
    private boolean isConnect = false;

    public boolean isWifiP2pEnable() {
        return wifiP2pEnable;
    }

    /**
     * Wifi有没有连接
     */
    public boolean isWifiP2pConnect() {
        return wifiP2pConnect;
    }

    /**
     * 有没有创建群
     */
    public boolean isGroupCreated() {
        if (wifiP2pDevice == null) {
            return false;
        }
        return wifiP2pDevice.status == WifiP2pDevice.CONNECTED;
    }


    @Override
    public void onWifiP2pStateChanged(boolean wifiP2pEnable) {
        this.wifiP2pEnable = wifiP2pEnable;
        if (connectListener != null) {
            connectListener.onWifiP2pStateChanged(wifiP2pEnable);
        }
    }

    @Override
    public void onPeersChanged() {
        if (connectListener != null) {
            connectListener.onPeersChanged();
        }
    }

    @Override
    public void onWifiP2pConnectionChanged(boolean wifiP2pConnect) {
        this.wifiP2pConnect = wifiP2pConnect;
        if (connectListener != null) {
            connectListener.onWifiP2pConnectionChanged(wifiP2pConnect);
        }
    }

    @Override
    public void onWifiP2pDeviceChanged(WifiP2pDevice wifiP2pDevice) {
        this.wifiP2pDevice = wifiP2pDevice;
        AddressManager.getInstance().onWifiP2pDeviceChanged(wifiP2pDevice);
        isConnect = wifiP2pDevice.status != WifiP2pDevice.AVAILABLE;
        if (isConnect) {
            WifiP2pCommon.getInstance().stopPeerDiscovery();
        } else {
            WifiP2pCommon.getInstance().discoverPeers();
        }
        if (connectListener != null) {
            connectListener.onWifiP2pDeviceChanged(wifiP2pDevice);
        }
    }

    /**
     * 设置连接监听
     */
    public void setConnectListener(IConnectListener connectListener) {
        this.connectListener = connectListener;
    }

    // 注册扫描Wifi的广播
    public void registerBroadcastReceiver(Context context) {
        if (context == null) {
            return;
        }
        if (connectionReceiver == null) {
            connectionReceiver = new ConnectionReceiver(this);
            context.registerReceiver(connectionReceiver, ConnectionReceiver.getIntentFilter());
        }
    }

    public void unregisterBroadcastReceiver(Context context) {
        if (context != null && connectionReceiver != null) {
            context.unregisterReceiver(connectionReceiver);
            connectionReceiver = null;
        }
    }

    public boolean isConnect() {
        return isConnect;
    }
}
